package cn.jsl.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 计时拦截器
 */
@Slf4j
@Component
public class TimingFilter implements GatewayFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //绑定了一个COUNT_Start_TIME参数   值就是当前的毫秒值
        //只要进到这个filter就马上执行
        exchange.getAttributes().put("COUNT_Start_TIME", System.currentTimeMillis());
        //chain.filter(exchange)--->就是执行下一个filter(放行)
        //.then--->什么时候会执行的  (当微服务处理完请求后  会原路返回   执行then里面的方法)
        return chain.filter(exchange).then(
            Mono.fromRunnable(() -> {
                //开始时间
                Long startTime = exchange.getAttribute("COUNT_Start_TIME");
                //结束时间
                Long endTime=(System.currentTimeMillis() - startTime);
                if (startTime != null) {
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                }
            })
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
